<template>
    <el-card shadow="always">
      <!-- 搜索 -->
      <Search :searchTitle="searchTitle" :searchForm="searchForm" @doSearch="getPageDatas" @doReset="reset"></Search>
      <!-- 身体 -->
      <div class="mt-3">
        <el-button class="mb-3" type="primary" size="small" @click="add">新增</el-button>
  
        <el-table :data="tableData" style="width: 100%" v-loading="loading">
          <el-table-column prop="title" label="优惠券名称" width="180" >
            <template #default="{ row }">
              <el-link :underline="false" type="primary" @click="router.push(`/notice/detail/${row.id}`)">{{ row.title }}</el-link>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="面值" width="180" />
          <el-table-column prop="image" label="封面" width="180" >
            <template #default="{ row }">
              <el-avatar shape="square" :size="40" :src="row.image" >
                <template #default>
                  暂无图片
                </template>
              </el-avatar>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="180">
            <template #default="{ row }">
                  <el-switch :modelValue="row.status" :active-value="1" :inactive-value="0"
                  @change="handleStatusChange($event,row)"
                  :loading="row.statusLoading"
                  :disabled="row.price=='122'"
                  >
                  </el-switch>
                  
              </template>
          </el-table-column>
          <el-table-column prop="add_time" label="添加时间">
            <template #default="{ row }">
              {{ formatTime(row.add_time) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button type="primary" text size="default" @click="update(scope.row)">编辑</el-button>
              <el-popconfirm title="确认删除？" confirm-button-text="确认" cancel-button-text="取消"
                @confirm="ydelete(scope.row.id)">
                <template #reference>
                  <el-button type="primary" text size="default">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
  
          <template #empty>
            <el-empty description="暂无数据"></el-empty>
          </template>
        </el-table>
      </div>
      <!-- 分页 flex items-center justify-center mt-5-->
      <div style="display: flex; justify-content: end; margin-top: 20px;" v-if="tableData.length>0">
        <el-pagination background v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="limit"
          :disabled="disabled" :background="background" layout="prev, pager, next, total, sizes, jumper" :total="total2"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
  
    </el-card>
    <!-- 弹窗 -->
    <Dialog :title="drawerTitle" @submit="handleSubmit" ref="formDrawerRef">
      <el-form :model="form" ref="formRef" :rules="rules" label-width="100px" :inline="false">
        <el-form-item label="优惠券名称" prop="title" width="">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="封面" prop="image">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleChange"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态" prop="status">
            <el-switch v-model="form.status" :active-value="1" :inactive-value="0"></el-switch>    
         </el-form-item>
        <el-form-item label="面值" prop="price">
          <el-input v-model="form.price"></el-input>
        </el-form-item>
      </el-form>
    </Dialog>
  
  
  </template>
  <script setup>
  import { ref, computed, reactive } from 'vue'
  import { youhuiquan } from '@/api/manager'
  import Dialog from "@/components/Dialog.vue"
  import Search from "@/components/Search.vue"
  import { formatTime } from '@/utils/dayjs'
  import { useRouter } from 'vue-router'
  import { updateDataClass, deleteDataClass,addDataClass } from '@/api/manager'
  const router = useRouter()
  // 图片
  const imageUrl = ref()
  
  const submitImage = ref()
  // 预览图片
  const handleChange = (file) => {
    imageUrl.value = URL.createObjectURL(file.raw)
    form.value.image = file.raw
  }
  
  
  // 搜索
  const searchTitle = ref("search")
  const searchForm = reactive({
    keyword: "",
  })
  const tableData = ref([])
  const disabled = ref(false)
  // 分页
  const total2 = ref(0)
  const currentPage = ref(1)
  const pageSize = ref(5)
  const limit = ref([5, 8, 10])
  const loading = ref(false)
  
  const handleSizeChange = (val) => {
    console.log(`${val} items per page`)
    pageSize.value = val;
    currentPage.value = 1; // 选择每页几条时，自动打到第一页重新计算数据
    getPageDatas()
  }
  const handleCurrentChange = (val) => {
    console.log(`current page: ${val}`)
    currentPage.value = val;
    getPageDatas()
  }
  
  // 获取数据+搜索
  const getPageDatas = () => {
    youhuiquan(currentPage.value, pageSize.value, searchForm.keyword)
      .then(res => {
        console.log(`优惠券数据：${JSON.stringify(res)}`)
        total2.value = res.totalCount
        tableData.value = res.list
      })
      .finally(() => {
        console.log(`tableData.value:${tableData.value}`)
  
      })
  }
  getPageDatas()
  
  // 重置
  const reset = () => {
    searchForm.keyword = ""
    currentPage.value = 1
    getPageDatas()
  }
  
  // 抽屉
  const editId = ref()
  const drawerTitle = computed(() => editId.value ? "编辑" : "新增")
  const formRef = ref(null)
  const formDrawerRef = ref(null) //调用子组件方法
  const form = ref({
    title: "",
    price: "",
    image: "",
    status: ""
  })
  const rules = ref({
    title: [{
      required: true,
      message: '优惠券名称不能为空',
      trigger: 'blur'
    }],
    price: [{
      required: true,
      message: '优惠券面值不能为空',
      trigger: 'blur'
    }],
  })
  // 删除
  const ydelete = (id) => {
    console.log(`id:${id}`)
    deleteDataClass({ "id": id }).then(res => {
    getPageDatas(currentPage.value=1)
    })
  }
  // 新增
  const add = () => {
    editId.value = 0
    form.value = {}
    imageUrl.value = ""
    formDrawerRef.value.open()
  }
  // 修改
  const update = (val) => {
    editId.value = 1
    console.log(`val:${val}`)
    form.value = {...val}
    imageUrl.value = val.image
    if (formRef.value) formRef.value.clearValidate()
    formDrawerRef.value.open()
  }
  // 新增+编辑接口
  const handleSubmit = () => {
    formRef.value.validate((valid) => {
      if (!valid) return
      formDrawerRef.value.showLoading()
      // 处理图片
      const formData = new FormData()
      for (let key in form.value) {
        formData.append(key, form.value[key])
      }
      const fun = editId.value ? updateDataClass(formData) : addDataClass(formData)
      // const fun = editId.value ? updateDataClass({"editId":editId.value,"form":form.value}) : addDataClass(form.value)
      fun.then(res=>{
          getPageDatas(editId.value ? currentPage.value : 1)
          formDrawerRef.value.close()
      })
      .finally(()=>{
          formDrawerRef.value.hideLoading()
      })
    })
  }
  tableData.value.map(o=>{
      o.statusLoading = false
    })
  // 修改状态
  const handleStatusChange=(status,row)=>{
    row.statusLoading = true
    console.log(`ststus:${status}`)
    console.log(`row:${row}`)
    row.status=status
    form.value.status = status
    row.statusLoading = false
  }
  </script>
  
  <style lang="scss" scoped>
  .avatar-uploader {
    :deep() {
      .avatar {
        width: 178px;
        height: 178px;
        display: block;
      }
      .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
      }
      .el-upload:hover {
        border-color: var(--el-color-primary);
      }
      .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
      }
    }
  }
  </style>